/**
 * 部门管理
 * Created by chenlin on 2017/12/20.
 */
define([
  './themes/lang/' + window.YUFP_SYS_CONFIG.language + '/pages/content/systemManager/dptManager/dptManager.js',
  './custom/widgets/js/YufpUserSelector.js',
  './custom/widgets/js/yufpOrgTree.js',
  './custom/widgets/js/yufpDptTree.js',
  './custom/widgets/js/yufpExtTree.js'
],
function (require, exports) {
  // page加载完成后调用ready方法
  exports.ready = function (hashCode, data, cite) {
    // 注册数据字典
    yufp.lookup.reg('DATA_STS');
    // 所属机构
    var belongOrgId = '';

    yufp.custom.vue({
      el: '#dptManager',
      data: function () {
        var me = this;
        return {
          formdata: {},
          dataRoot: { orgId: yufp.session.org.id, orgName: yufp.session.org.name },
          orgTreeUrl: backend.appOcaService + '/api/util/getorg',
          dataParams: { userId: yufp.session.userId, needManage: true, orgSts: 'A', lazy: true },
          dptTableUrl: backend.appOcaService + '/api/adminsmdpt/list',
          dptTableParam: {
            condition: JSON.stringify({
              belongOrgId: yufp.session.org.id
            })
          },
          dptUserUrl: backend.appOcaService + '/api/adminsmdpt/userlist',
          addButton: !yufp.session.checkCtrl('add'), // 新增按钮控制
          modifyButton: !yufp.session.checkCtrl('modify'), // 修改按钮控制
          deleteButton: !yufp.session.checkCtrl('delete'), // 删除按钮控制
          enableButton: !yufp.session.checkCtrl('enable'), // 启用按钮控制
          disableButton: !yufp.session.checkCtrl('disable'), // 停用按钮控制
          dptUserButton: !yufp.session.checkCtrl('dptUser'), // 部门用户按钮控制
          expandCollapseName: ['base'],
          tableColumns: [
            { label: this.$t('dptManager.ssjg'), prop: 'orgName' },
            { label: this.$t('dptManager.bmdm'), prop: 'dptCde' },
            {
              label: this.$t('dptManager.bmmc'),
              prop: 'dptName',
              sortable: true,
              resizable: true,
              template: function () {
                return '<template scope="scope">\
                                <a onclick="return false;" href="javascipt:void(0);" style="text-decoration:underline;" @click="_$event(\'custom-detail-click\', scope)">{{ scope.row.dptName }}</a>\
                            </template>';
              }
            },
            { label: this.$t('dptManager.zt'), prop: 'dptSts', width: 80, dataCode: 'DATA_STS' },
            { label: this.$t('dptManager.sjbm'), prop: 'upDptName' },
            { label: this.$t('dptManager.zxgxr'), prop: 'userName' },
            {
              label: this.$t('dptManager.zxbgsj'),
              prop: 'lastChgDt',
              width: 110,
              formatter: function (row, me) {
                return row.lastChgDt.substring(0, 10);
              }
            }
          ],
          updateFields: [{
            columnCount: 1,
            fields: [
              {
                label: this.$t('dptManager.bmdm'),
                field: 'dptCde',
                rules: [{ required: true, message: this.$t('dptManager.btx'), trigger: 'blur' },
                  { max: 33, message: this.$t('dptManager.srzgc'), trigger: 'blur' },
                  {
                    validator: yufp.validator.numberAndLetter,
                    trigger: 'blur',
                    message: this.$t('dptManager.znsrzmysz')
                  }]
              },
              {
                label: this.$t('dptManager.bmmc'),
                field: 'dptName',
                rules: [{ required: true, message: this.$t('dptManager.btx'), trigger: 'blur' },
                  { max: 33, message: this.$t('dptManager.srzgc'), trigger: 'blur' }]
              },
              {
                label: this.$t('dptManager.ssjg'),
                field: 'belongOrgId',
                type: 'custom',
                is: 'yufp-org-tree',
                params: {
                  lazy: true,
                  needCheckbox: false,
                  dataRoot: { orgId: yufp.session.org.id, orgName: yufp.session.org.name },
                  dataParams: {
                    userId: yufp.session.userId,
                    needManage: true,
                    orgSts: 'A',
                    lazy: true
                  }
                },
                rules: [{ required: true, message: this.$t('dptManager.btx'), trigger: 'blur' }],
                selectFn: function (code, data, arry) {
                  var temp = yufp.clone(me.updateFields[0].fields[3].params);
                  temp.dataParams = {
                    orgCode: code
                  };
                  me.updateFields[0].fields[3].params = yufp.clone(temp);
                }
              },
              {
                label: this.$t('dptManager.sjbm'),
                field: 'upDptId',
                type: 'custom',
                is: 'yufp-dpt-tree',
                params: {
                  dataUrl: backend.appOcaService + '/api/util/getdpt',
                  // dataRoot: '10000001',
                  dataId: 'orgCode',
                  needCheckbox: false
                }, //
                selectFn: function (code, data, arry) {
                }
              },
              {
                label: this.$t('dptManager.zt'),
                field: 'dptSts',
                type: 'select',
                dataCode: 'DATA_STS',
                rules: [{ required: true, message: this.$t('dptManager.btx'), trigger: 'blur' }]
              },
              { field: 'userName', label: this.$t('dptManager.zxgxr') },
              { field: 'lastChgDt', label: this.$t('dptManager.zxgxsj') }
            ]
          }],
          updateButtons: [
            {
              label: this.$t('dptManager.bc'),
              type: 'primary',
              op: 'submit',
              hidden: false,
              click: function (model) {
                me.saveCreateFn();
              }
            },
            {
              label: this.$t('dptManager.bc'),
              type: 'primary',
              op: 'submit',
              hidden: false,
              click: function (model) {
                me.saveEditFn();
              }
            },
            {
              label: this.$t('dptManager.qx'),
              hidden: false,
              click: function (model) {
                me.dialogVisible = false;
              }
            }],
          height: yufp.custom.viewSize().height - 10,
          dialogVisible: false,
          formDisabled: false,
          viewType: 'DETAIL',
          viewTitle: yufp.lookup.find('CRUD_TYPE', false),
          // 用户列表弹窗
          dialogGridVisible: false, // 列表弹窗
          textMap: {
            dptUser: this.$t('dptManager.bmyh')
          },
          userQueryFields: [
            { placeholder: this.$t('dptManager.dldm'), field: 'loginCode', type: 'input' },
            { placeholder: this.$t('dptManager.ygxm'), field: 'userName', type: 'input' },
            { placeholder: this.$t('dptManager.ygh'), field: 'userCode', type: 'input' }
          ],
          userQueryButtons: [
            {
              label: this.$t('dptManager.ss'),
              op: 'submit',
              type: 'primary',
              click: function (model, valid) {
                if (valid) {
                  var param = {
                    condition: JSON.stringify({
                      loginCode: me.$refs.userQuery.fm.loginCode ? me.$refs.userQuery.fm.loginCode : null,
                      userName: me.$refs.userQuery.fm.userName ? me.$refs.userQuery.fm.userName : null,
                      userCode: me.$refs.userQuery.fm.userCode ? me.$refs.userQuery.fm.userCode : null,
                      userSts: me.$refs.userQuery.fm.userSts ? me.$refs.userQuery.fm.userSts : null,
                      dptId: me.$refs.dptTable.selections[0].dptId
                    })
                  };
                  me.$refs.userTable.remoteData(param);
                }
              }
            },
            {
              label: this.$t('dptManager.zz'),
              op: 'reset',
              click: function () {
              }
            }
          ],
          userTableColumns: [
            { label: this.$t('dptManager.dldm'), prop: 'loginCode' },
            { label: this.$t('dptManager.ygxm'), prop: 'userName', sortable: true, resizable: true }
          ]
        };
      },
      methods: {
        // 主列表
        queryMainGridFn: function () { // 列表查询
          var me = this;
          var param = {
            condition: JSON.stringify({
              dptCde: me.formdata.dptCde ? me.formdata.dptCde : null,
              dptName: me.formdata.dptName ? me.formdata.dptName : null,
              dptSts: me.formdata.dptSts ? me.formdata.dptSts : null,
              belongOrgId: me.formdata.belongOrgId
            })
          };
          me.$refs.dptTable.remoteData(param);
        },
        switchStatus: function (viewType, editable) { // 初始面板标题、按钮等信息
          this.viewType = viewType;
          this.dialogVisible = true;
          this.formDisabled = !editable;
          this.updateButtons[2].hidden = !editable;
          if (viewType == 'ADD') {
            this.updateButtons[0].hidden = !editable;
            this.updateButtons[1].hidden = editable;
          } else if (viewType == 'EDIT') {
            this.updateButtons[0].hidden = editable;
            this.updateButtons[1].hidden = !editable;
          } else if (viewType == 'DETAIL') {
            this.updateButtons[0].hidden = !editable;
            this.updateButtons[1].hidden = !editable;
          }
        },
        nodeClickFn: function (nodeData, node, self) { // 树点击事件
          /* 初始化部门数据*/
          var temp = yufp.clone(this.updateFields[0].fields[3].params);
          temp.dataParams = {
            orgCode: nodeData.orgId
          };
          this.updateFields[0].fields[3].params = yufp.clone(temp);
          // 查询
          this.formdata.belongOrgId = nodeData.orgId;
          belongOrgId = nodeData.orgId;
          this.queryMainGridFn();
        },
        addFn: function () { // 新增弹出方法
          this.switchStatus('ADD', true);
          this.$nextTick(function () {
            this.$refs.dptForm.resetFields();// 重置form
            this.$refs.dptForm.formModel.dptSts = 'A';// 设置默认值
            this.$refs.dptForm.formModel.belongOrgId = belongOrgId;
            // 初始化部门树
            var temp = yufp.clone(this.updateFields[0].fields[3].params);
            temp.dataParams = {
              orgCode: belongOrgId
            };
            this.updateFields[0].fields[3].params = yufp.clone(temp);
            // 设置编号可编辑
            this.updateFields[0].fields[0].readonly = false;
            // 设置字段隐藏
            this.updateFields[0].fields[5].hidden = true;
            this.updateFields[0].fields[6].hidden = true;
          });
        },
        modifyFn: function () { // 修改弹出方法
          if (this.$refs.dptTable.selections.length != 1) {
            this.$message({ message: this.$t('dptManager.qxzytjl'), type: 'warning' });
            return;
          }
          if (this.$refs.dptTable.selections[0].dptSts == 'A') {
            this.$message({ message: this.$t('dptManager.znxzsxhdsxdsj'), type: 'warning' });
            return;
          }
          this.switchStatus('EDIT', true);
          this.$nextTick(function () {
            yufp.extend(this.$refs.dptForm.formModel, this.$refs.dptTable.selections[0]);
            // 设置编号不可编辑
            this.updateFields[0].fields[0].readonly = true;
            // 设置字段隐藏
            this.updateFields[0].fields[5].hidden = true;
            this.updateFields[0].fields[6].hidden = true;
          });
        },
        infoFn: function (row) { // 详情弹出方法
          // 设置字段隐藏
          this.updateFields[0].fields[5].hidden = false;
          this.updateFields[0].fields[6].hidden = false;
          this.switchStatus('DETAIL', false);
          this.$nextTick(function () {
            yufp.extend(this.$refs.dptForm.formModel, row.row);
          });
        },
        saveCreateFn: function () { // 新增保存方法
          var me = this;
          var fields = me.$refs.dptForm;
          delete fields.formModel.dptId;
          fields.formModel.lastChgUsr = yufp.session.userId;// 最新更新人
          this.$refs.dptForm.validate(function (valid) {
            if (valid) {
              yufp.service.request({
                method: 'GET',
                url: backend.appOcaService + '/api/adminsmdpt/checkdptcde',
                data: {
                  dptCde: fields.formModel.dptCde
                },
                callback: function (code, message, response) {
                  if (response > 0) {
                    me.$message({ message: me.$t('dptManager.gbmbhcfqxg'), type: 'warning' });
                  } else {
                    yufp.service.request({
                      method: 'POST',
                      url: backend.appOcaService + '/api/adminsmdpt/adddpt',
                      data: fields.formModel,
                      callback: function (code, message, response) {
                        me.dialogVisible = false;
                        me.$message({ message: me.$t('dptManager.sjbccg') });
                        me.queryMainGridFn();
                      }
                    });
                  }
                }
              });
            }
          });
        },
        saveEditFn: function () { // 修改保存方法
          var fields = this.$refs.dptForm;
          var me = this;
          fields.formModel.lastChgUsr = yufp.session.userId;// 最新更新人
          this.$refs.dptForm.validate(function (valid) {
            if (valid) {
              yufp.service.request({
                method: 'POST',
                url: backend.appOcaService + '/api/adminsmdpt/update',
                data: fields.formModel,
                callback: function (code, message, response) {
                  me.dialogVisible = false;
                  me.$message({ message: me.$t('dptManager.sjbccg') });
                  me.queryMainGridFn();
                }
              });
            }
          });
        },
        useFn: function () { // 批量启用
          var me = this;
          if (this.$refs.dptTable.selections.length > 0) {
            var id = '';
            for (var i = 0; i < this.$refs.dptTable.selections.length; i++) {
              var row = this.$refs.dptTable.selections[i];
              if (row.dptSts === 'W' || row.dptSts === 'I') {
                id = id + ',' + row.dptId;
              } else {
                this.$message({ message: this.$t('dptManager.znxzsxhdsxdsj'), type: 'warning' });
                return;
              }
            }
            this.$confirm(this.$t('dptManager.cczjsxbmsxsfjx'), this.$t('dptManager.ts'), {
              confirmButtonText: this.$t('dptManager.qd'),
              cancelButtonText: this.$t('dptManager.qx'),
              type: 'warning',
              center: true
            }).then(function () {
              yufp.service.request({
                method: 'POST',
                url: backend.appOcaService + '/api/adminsmdpt/usebatch',
                data: {
                  id: id,
                  userId: yufp.session.userId
                },
                callback: function (code, message, response) {
                  me.$message({ message: response.message });
                  me.queryMainGridFn();
                }
              });
            });
          } else {
            me.$message({ message: me.$t('dptManager.qxxzysxdsj'), type: 'warning' });
            return;
          }
        },
        unUseFn: function () { // 批量失效
          var me = this;
          if (this.$refs.dptTable.selections.length > 0) {
            var id = '';
            for (var i = 0; i < this.$refs.dptTable.selections.length; i++) {
              var row = this.$refs.dptTable.selections[i];
              if (row.dptSts === 'A') {
                id = id + ',' + row.dptId;
              } else {
                this.$message({ message: this.$t('dptManager.znxzsxdsj'), type: 'warning' });
                return;
              }
            }
            this.$confirm(this.$t('dptManager.cczjsxbmsxsfjx'), this.$t('dptManager.ts'), {
              confirmButtonText: this.$t('dptManager.qd'),
              cancelButtonText: this.$t('dptManager.qx'),
              type: 'warning',
              center: true
            }).then(function () {
              yufp.service.request({
                method: 'POST',
                url: backend.appOcaService + '/api/adminsmdpt/unusebatch',
                data: {
                  id: id,
                  userId: yufp.session.userId
                },
                callback: function (code, message, response) {
                  if (code == 0) {
                    me.$message({ message: response.message });
                    me.queryMainGridFn();
                  }
                }
              });
            });
          } else {
            me.$message({ message: me.$t('dptManager.qxxzysxdsj'), type: 'warning' });
            return;
          }
        },
        deleteFn: function () { // 批量删除
          var me = this;
          if (this.$refs.dptTable.selections.length > 0) {
            var id = '';
            for (var i = 0; i < this.$refs.dptTable.selections.length; i++) {
              var row = this.$refs.dptTable.selections[i];
              if (row.dptSts != 'A') {
                id = id + ',' + row.dptId;
              } else {
                this.$message({ message: this.$t('dptManager.znscdsxhsxdsj'), type: 'warning' });
                return;
              }
            }
            me.$confirm(me.$t('dptManager.cczjscgbmxxsfjx'), me.$t('dptManager.ts'), {
              confirmButtonText: me.$t('dptManager.qd'),
              cancelButtonText: me.$t('dptManager.qx'),
              type: 'warning',
              center: true
            }).then(function () {
              yufp.service.request({
                method: 'POST',
                url: backend.appOcaService + '/api/adminsmdpt/deletebatch',
                data: {
                  id: id
                },
                callback: function (code, message, response) {
                  if (code == '0') {
                    me.$message({ message: response.message });
                    me.queryMainGridFn();
                  }
                }
              });
            }).catch(function () {
              return;
            });
          } else {
            me.$message({ message: me.$t('dptManager.qxxzyscdsj'), type: 'warning' });
            return;
          }
        },
        // 部门用户列表弹窗
        openDptUserFn: function () { // 打开部门用户列表
          if (this.$refs.dptTable.selections.length != 1) {
            this.$message({ message: this.$t('dptManager.qxxzytjl'), type: 'warning' });
            return;
          }
          this.dialogDisabled = false;
          this.dialogStatus = 'dptUser';
          this.dialogGridVisible = true;
          this.queryUserGridFn();
        },
        queryUserGridFn: function () { // 部门用户列表
          var me = this;
          this.$nextTick(function () {
            var param = {
              condition: JSON.stringify({
                loginCode: me.$refs.userQuery.fm.loginCode ? me.$refs.userQuery.fm.loginCode : null,
                userName: me.$refs.userQuery.fm.userName ? me.$refs.userQuery.fm.userName : null,
                userCode: me.$refs.userQuery.fm.userCode ? me.$refs.userQuery.fm.userCode : null,
                userSts: me.$refs.userQuery.fm.userSts ? me.$refs.userQuery.fm.userSts : null,
                dptId: me.$refs.dptTable.selections[0].dptId
              })
            };
            me.$refs.userTable.remoteData(param);
          });
        }
      }
    });
  };
});
